package com.example.bigevent.controller;


import com.example.bigevent.pojo.Result;
import com.example.bigevent.pojo.User;
import com.example.bigevent.service.UserService;
import com.example.bigevent.utils.JwtUtils;
import com.example.bigevent.utils.Md5Util;
import com.example.bigevent.utils.ThreadLocatUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        // 查询用户是否存在
        User u = userService.findByUserName(username);
        if (u == null) {
            // 用户不存在，注册
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();
        // 根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("该用户不存在");
        } else {
            // 验证密码
            if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
                // 生成 JWT 令牌
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", loginUser.getId());
                claims.put("username", loginUser.getUsername());
                String jwt = JwtUtils.generateJwt(claims);
                // jwt 存入 redis
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(jwt, jwt, 12, TimeUnit.HOURS);
                return Result.success(jwt);
            }
            return Result.error("密码错误");
        }
    }

    @GetMapping("/userInfo")
    public Result userInfo() {
        Map<String, Object> map = ThreadLocatUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }


    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        System.out.println(avatarUrl);
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("token") String jwt) {
        // 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("参数不能为空");
        }
        Map<String, Object> map = ThreadLocatUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        // 校验旧密码
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码错误");
        }
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的密码不一致");
        }
        userService.updatePwd(newPwd);
        // 删除 redis 中的 jwt
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(jwt);

        return Result.success();
    }
}
